package com.tl.sun.utils;

import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Base64;

import com.tl.sun.helper.UIHelper;
import com.tl.sun.model.PayInfo;
import com.tl.sun.utils.common.EncryptUtils;
import com.tl.sun.utils.common.MD5Util;
import com.orhanobut.logger.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by librabin on 16/11/15.
 */

public class MDUtil {

    private final static String KEY = "lingjiang.com";
    private final static String KEYS = "OjGeRaYro0VRNDpzMX6zFD9h0PbOIhZohYZ9pjOJLOCkIPSU3eCZCxzddEvmkplQ";

    public static void webCall(Context context, String jsonStr) {
        try {
            Logger.e(jsonStr);
            JSONObject jsonObject = new JSONObject(jsonStr);
            String cmd = jsonObject.optString("action");
            String infoStr = jsonObject.optString("info");
            if (cmd.equalsIgnoreCase("act_update")) {
//                UIHelper.checkUpdate(context, true);

            } else if (cmd.equalsIgnoreCase("act_scan")) {
//                UIHelper.showScan((FragmentActivity)context);
            } else if (cmd.equalsIgnoreCase("act_share")) {
//                ShareInfo shareInfo = new ShareInfo();
//                JSONObject infoJson = new JSONObject(infoStr);
//                ShareInfo.ShareInfoParser(infoJson, shareInfo);
//                UIHelper.postShare((FragmentActivity) context, shareInfo);
            } else if (cmd.equalsIgnoreCase("act_pay")) {
                PayInfo payInfo = new PayInfo();
                JSONObject infoJson = new JSONObject(infoStr);
                PayInfo.PayInfoParser(infoJson, payInfo);
                UIHelper.doPay((FragmentActivity) context, payInfo);
            } else if (cmd.equalsIgnoreCase("act_print")) {
//                CLog.e(TAG, "print info: " + infoStr);
//                OrderInfo orderInfo = new OrderInfo();
//                JSONObject infoJson = new JSONObject(infoStr);
//                OrderInfo.OrderInfoParser(infoJson, orderInfo);
//                UIHelper.printOrder((AppCompatAtivity)context, orderInfo);
            } else {
                ToastUtil.showToast("不支持");
            }
        } catch (JSONException e) {
            ToastUtil.showToast("出错了");
        }
    }


    public static void mdTest() {
//        mdEncrypt("test");
        try {
            mdDecrypt(mdEncrypt1("111"));
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }

    }


    public static String mdEncrypt1(String str) {
        String str1 = "1111111111111";
        String str2 = "aaaaaaaaaaaaa";
        String str3 = KEY;
        String str4 = EncryptUtils.encryptMD5ToString(str1 + str2 + str3).toLowerCase();
        //待加密内容base64转码为String
        String str5 = new String(Base64.encode(str.getBytes(), Base64.NO_WRAP));

        // 5用4异或
        String str6_1 = doEor(str5, str4);

        String str6_2 = doEor(str1, str2);

        String str6_3 = doEor(str2, str3);

        String finalStr = new String(Base64.encode((str6_1 + str6_2 + str6_3).getBytes(), Base64.NO_WRAP));
        Logger.e(finalStr);

        return finalStr;


    }


    public static String mdEncrypt(String str) {
        String str1 = System.currentTimeMillis() + 120000 + "";
        String str2 = getRandomString(13);
        String str3 = KEY;
        String str4 = EncryptUtils.encryptMD5ToString(str1 + str2 + str3).toLowerCase();
        //待加密内容base64转码为String
        String str5 = new String(Base64.encode(str.getBytes(), Base64.NO_WRAP));

        // 5用4异或
        String str6_1 = doEor(str5, str4);

        String str6_2 = doEor(str1, str2);

        String str6_3 = doEor(str2, str3);

        String finalStr = new String(Base64.encode((str6_1 + str6_2 + str6_3).getBytes(), Base64.NO_WRAP));

        return finalStr;


    }

    public static String mdEncrypts(String str) {
        String str1 = System.currentTimeMillis() + 120000 + "";
        String str2 = getRandomString(13);
        String str3 = KEYS;
        String str4 = EncryptUtils.encryptMD5ToString(str1 + str2 + str3).toLowerCase();
        //待加密内容base64转码为String
        String str5 = new String(Base64.encode(str.getBytes(), Base64.NO_WRAP));

        // 5用4异或
        String str6_1 = doEor(str5, str4);

        String str6_2 = doEor(str1, str2);

        String str6_3 = doEor(str2, str3);

        String finalStr = new String(Base64.encode((str6_1 + str6_2 + str6_3).getBytes(), Base64.NO_WRAP));
        return finalStr;
    }

    /**
     * 解密
     *
     * @param str
     * @return
     */
    public static String mdDecrypt(String str) {
        String finalStr = new String(Base64.decode(str.getBytes(), Base64.NO_WRAP));
        // String str2 = KEY;
        String str2 = "zhimadaili";
        String str3_1 = doEor(finalStr.substring(finalStr.length() - 13), str2);
        String str3_2 = doEor(finalStr.substring(finalStr.length() - 26, finalStr.length() - 13), str3_1);
        String str3_3 = EncryptUtils.encryptMD5ToString(str3_2 + str3_1 + str2).toLowerCase();

        String testStr = doEor(finalStr.substring(0, finalStr.length() - 26), str3_3);

        String testStr2 = new String(Base64.decode(testStr.getBytes(), Base64.NO_WRAP));

//        Logger.e("eee" + testStr2);

        return testStr2;
    }


    private static String doEor(String str1, String str2) {
        char[] array1 = str1.toCharArray();
        char[] array2 = str2.toCharArray();
        char[] array3 = new char[array1.length];

        for (int i = 0; i < array1.length; i++) {
            array3[i] = (char) (array1[i] ^ array2[i % str2.length()]);
        }

        return new String(array3);

    }


    private static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }


    /**
     * 获取IP地址
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
     *
     * @param useIPv4 是否用IPv4
     * @return IP地址
     */
    public static String getIPAddress(final boolean useIPv4) {
        try {
            for (Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); nis.hasMoreElements(); ) {
                NetworkInterface ni = nis.nextElement();
                // 防止小米手机返回10.0.2.15
                if (!ni.isUp()) continue;
                for (Enumeration<InetAddress> addresses = ni.getInetAddresses(); addresses.hasMoreElements(); ) {
                    InetAddress inetAddress = addresses.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String hostAddress = inetAddress.getHostAddress();
                        boolean isIPv4 = hostAddress.indexOf(':') < 0;
                        if (useIPv4) {
                            if (isIPv4) return hostAddress;
                        } else {
                            if (!isIPv4) {
                                int index = hostAddress.indexOf('%');
                                return index < 0 ? hostAddress.toUpperCase() : hostAddress.substring(0, index).toUpperCase();
                            }
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getSignMD5(Map<String, String> params) {
        Collection<String> keySet = params.keySet();
        List<String> list = new ArrayList<>(keySet);

        Collections.sort(list);
        String paramStr = "";
        for (int i = 0; i < list.size(); i++) {
            String value = params.get(list.get(i).trim());
            if (TextUtils.isEmpty(value)) {
                continue;
            }
            paramStr += list.get(i) + "=" + params.get(list.get(i)) + "&";
        }

        if (!TextUtils.isEmpty(paramStr)) {
            paramStr = paramStr.substring(0, paramStr.length() - 1);
        }
        //MD5签名
        String s = MD5Util.md5(paramStr + "PqTgfCM00i73brLBh9f7");
        return s;
    }
}
